package com.hc.gen.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.hc.common.datasource.BaseDataSourceData;
import com.hc.common.datasource.DynamicSaasDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "spring.datasource.dynamic")
public class datasourceConfig {
    private List<BaseDataSourceData> datasourceList;

    @Bean
    @RefreshScope
    public DynamicSaasDataSource dataSource () {
        Map<Object, Object> targetDataSources = new HashMap<>();
        for(int i=0;i<datasourceList.size();i++){
            DruidDataSource druidDataSource = setProperties(datasourceList.get(i));
            targetDataSources.put(datasourceList.get(i).getName(),druidDataSource);
        }
        return new DynamicSaasDataSource((DataSource) targetDataSources.get("admin"),targetDataSources);

    }

    private DruidDataSource setProperties(BaseDataSourceData baseDataSourceData) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        dataSource.setUrl(baseDataSourceData.getUrl());
        dataSource.setUsername(baseDataSourceData.getUsername());
        dataSource.setPassword(baseDataSourceData.getPassword());
        return dataSource;
    }

    public List<BaseDataSourceData> getDatasourceList() {
        return datasourceList;
    }

    public void setDatasourceList(List<BaseDataSourceData> datasourceList) {
        this.datasourceList = datasourceList;
    }
}
